package com.framework.modules.job.utils;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.*;

import com.framework.entity.job.ScheduleJobEntity;
import com.framework.entity.job.ScheduleJobLogEntity;
import com.framework.modules.job.service.ScheduleJobLogService;
import com.framework.utils.MapUtils;
import com.framework.utils.SpringContextUtils;
import com.framework.utils.json.JsonUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;


/**
 * 定时任务
 */
public class ScheduleJob extends QuartzJobBean {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private ExecutorService service = new ThreadPoolExecutor(1, 1,
			0L, TimeUnit.MILLISECONDS,
			new LinkedBlockingQueue<Runnable>());

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		Object object = context.getMergedJobDataMap().get(ScheduleJobEntity.JOB_PARAM_KEY);
		Map<String,Object> map = new HashedMap();
		try {
			map = MapUtils.objectToMap(object);
			System.out.println(map);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		//填充参数
		ScheduleJobEntity scheduleJob = new ScheduleJobEntity();
		scheduleJob.setBeanName((String)map.get("beanName"));
		scheduleJob.setJobId((Long)map.get("jobId"));
		scheduleJob.setCreateTime((Date)map.get("createTime"));
		scheduleJob.setCronExpression((String)map.get("cronExpression"));
		scheduleJob.setMethodName((String)map.get("methodName"));
		scheduleJob.setParams((String)map.get("params"));
		scheduleJob.setRemark((String)map.get("remark"));
		scheduleJob.setStatus((Integer)map.get("status"));
		// 获取spring bean
		ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtils.getBean("scheduleJobLogService");
		// 数据库保存执行记录
		ScheduleJobLogEntity log = new ScheduleJobLogEntity();
		log.setJobId(scheduleJob.getJobId());
		log.setBeanName(scheduleJob.getBeanName());
		log.setMethodName(scheduleJob.getMethodName());
		log.setParams(scheduleJob.getParams());
		log.setCreateTime(new Date());

		// 任务开始时间
		long startTime = System.currentTimeMillis();

		try {
			// 执行任务
			logger.info("任务准备执行，任务ID：" + scheduleJob.getJobId());
			ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(), scheduleJob.getMethodName(), scheduleJob.getParams());
			Future<?> future = service.submit(task);

			future.get();

			// 任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			log.setTimes((int) times);
			// 任务状态 0：成功 1：失败
			log.setStatus(0);

			logger.info("任务执行完毕，任务ID：" + scheduleJob.getJobId() + "  总共耗时：" + times + "毫秒");
		} catch (Exception e) {
			logger.error("任务执行失败，任务ID：" + scheduleJob.getJobId(), e);

			// 任务执行总时长
			long times = System.currentTimeMillis() - startTime;
			log.setTimes((int) times);

			// 任务状态 0：成功 1：失败
			log.setStatus(1);
			log.setError(StringUtils.substring(e.toString(), 0, 2000));
		} finally {
			scheduleJobLogService.insert(log);
		}
	}
}
